package com.lhm.controller;


import com.lhm.entity.*;
import com.lhm.service.*;
import com.lhm.tool.RespJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@CrossOrigin
@RestController
@RequestMapping("/api/public")
public class PubleController {
    @Autowired
    HotService hotService;
    @Autowired
    BookService bookService;
    @Autowired
    UserService userService;
    @Autowired
    LargeFileService largeFileService;
    @Autowired
    BookTypeService bookTypeService;
    @Autowired
    CartService cartService;

///api/public/findHot/{num}/{type}
    @RequestMapping("/findHot/{num}/{type}")
    public Map<String,Object> findHot(@PathVariable("num") int num, @PathVariable("type") int type){
//        select *  from t_hot  where type=#{type} order by hot limit 0, #{num}
        List<Hot> lst = hotService.findByType(type , num );
        return RespJson.pack(200,"获取成功",lst);
    }
//模糊查找 书名  出版社  作者
    @RequestMapping("/book/findIf/{start}/{num}")
    public Map<String, Object> findBookIf(@PathVariable("start") Integer start, @PathVariable("num") Integer num, String key) {
        System.out.println("start=" + start + "  num=" + num + "  key=" + key);
        if (key == null || key.length() < 2)
            return RespJson.pack(100, "搜索关键字不能短于 2  ", null);
        List<Book> lst = bookService.findByName(key, start, num);
                //  查询总数量
        int total = bookService.getCountByName(key);
        Map<String, Object> map = new HashMap<>();
        map.put("books", lst);
        map.put("total", total);
        return RespJson.pack(200, "", map);
    }

    //添加
    @RequestMapping("/addUser")
    public Map<String, Object> register(@RequestBody MyUser u) {
        System.out.println("添加普通用户=" + u);
        new HashMap();
        u.setRole("P");
        this.userService.add(u);
        return RespJson.pack(200, "注册成功 ...", null);
    }
//  分页查找书本信息
    @RequestMapping("/findBookByPage/{start}/{num}/{typeid}")
    public Map<String, Object> findPages_book(@PathVariable("start") Integer start, @PathVariable("num") Integer num, @PathVariable("typeid") Integer typeid) {
        Map<String, Object> map = new HashMap<>();
        List<Book> lst =bookService.findPage(start*num, num, typeid);
        map.put("books", lst);
        int count = bookService.getCount(typeid);
        map.put("total", count);
        return RespJson.pack(200, "", map);
    }

    //显示
    @RequestMapping("/showImg/{id}")
    public void dispaly(@PathVariable("id") String id, HttpServletResponse response) {
        byte[] buf;
        if (id == null)
            return;
        LargeFile largeFile = largeFileService.findById(id);
        try {
            buf = (byte[])largeFile.getContent();
        } catch (NullPointerException e) {
            buf = new byte[1];
        }
        try {
            response.setContentType("image/jpeg");
            response.getOutputStream().write(buf);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
// 查找所有的书本类型
    @RequestMapping("/type/findAll")
    public Map<String, Object> getBookTypes() {
        List<BookType> types = bookTypeService.findAll();
        return RespJson.pack(200, "", types);
    }
    ///api/public/book/findRate5     获得点赞前 5 的商品
    @RequestMapping({"/book/findRate5"})
    public Map<String, Object> findRate5() {
        List<Book> lst = this.bookService.findRate5();

        return RespJson.pack(200, "", lst);
    }
///api/public/book/findSale5   获得点销量 5 的商品
    @RequestMapping("/book/findSale5")
    public Map<String,Object> findSale5(){
        List<Book> lst = bookService.findSale5();
        return RespJson.pack(200,"",lst);
    }
///api/public/book/findFav5 获得点加到购物车前 5 的商品
    @RequestMapping("/book/findFav5")
    public Map<String,Object> findFav5(){
        List<Book> lst = bookService.findFav5();
        return RespJson.pack(200,"",lst);
    }
// 分页查找书本信息并按照点赞从高到低排序
    @RequestMapping("/findBookByPageRate/{start}/{num}/{typeid}")
    public Map<String,Object> findBookByPageRate(@PathVariable("start") Integer start, @PathVariable("num") Integer num, @PathVariable("typeid") Integer typeid){
        Map<String, Object> map = new HashMap<>();
        List<Book> lst = bookService.findPageRate(start*num, num, typeid);
        map.put("books", lst);
        int count = bookService.getCount(typeid);
        map.put("total", count);
        return RespJson.pack(200, "", map);
    }
//  分页查找书本信息并按照销量从高到低排序
    @RequestMapping("/findBookByPageSale/{start}/{num}/{typeid}")
    public Map<String,Object> findBookByPageSale(@PathVariable("start") Integer start, @PathVariable("num") Integer num, @PathVariable("typeid") Integer typeid){
        Map<String, Object> map = new HashMap<>();
        List<Book> lst =bookService.findPageSale(start*num, num, typeid);
        map.put("books", lst);
        int count = bookService.getCount(typeid);
        map.put("total",count);
        return RespJson.pack(200, "", map);
    }
//分页查找书本信息并按照购物车从高到低
    @RequestMapping("/findBookByPageFav/{start}/{num}/{typeid}")
    public Map<String,Object> findBookByPageFav(@PathVariable("start") Integer start, @PathVariable("num") Integer num, @PathVariable("typeid") Integer typeid){
        Map<String, Object> map = new HashMap<>();
        List<Book> lst = bookService.findPageFav(start*num, num, typeid);
        map.put("books", lst);
        int count = bookService.getCount(typeid);
        map.put("total", count);
        return RespJson.pack(200, "", map);
    }
    //根据 getUser 拿到Token相应的登录用户的账号
    public static Object getUser(){
        Object object = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return object;
    }
    //加入购物车
    @RequestMapping("/addCart/{bookid}")
    public Map<String, Object> goCart(@PathVariable("bookid") int bookid) {
        new HashMap();
        MyUser mu= (MyUser) getUser();//根据myuser 拿到Token相对应的id
        System.out.println(mu);//打印一下mu
        int uid=mu.getId();
        if (uid < 0) {
            return RespJson.pack(401, "你未登录， 请登录 .....", 0);
        } else {
            Cart c = new Cart();
            c.setBookid(bookid);
            c.setUid(uid);
            c.setNum(1);
            cartService.add(c);
            return RespJson.pack(200, "加入购物车成功 ...", null);
        }
    }

    /**
     * 自动转换日期类型的字段格式
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }
}
